// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.preferencessync.internal.merge;

import com.google.appengine.preferencessync.internal.InternalSyncException;
import com.google.appengine.preferencessync.internal.SharedPreferencesUtils;
import com.google.appengine.syncserver.shared.PropertyChange;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.ArrayList;

/**
 * Server wins handler.
 */
public class ServerWinsHandler implements InternalMergeHandler {

  /**
   * Applies all server changes to the client.
   */
  @Override
  public void merge(SharedPreferences clientPreferences, ArrayList<PropertyChange> clientChanges,
      ArrayList<PropertyChange> serverChanges) throws InternalSyncException {
    Editor editor = clientPreferences.edit();
    
    // Since server wins just apply the server changes.
    for (PropertyChange change : serverChanges) {
      switch(change.getType()) {
        case DELETE:
          editor.remove(change.getKey());
          break;

        case UPDATE:
          SharedPreferencesUtils.putNamespacedStringAsObject(editor, change.getKey(),
              change.getValue());
          break;
      }
    }
    editor.commit();
  }
}
